import Koa from 'koa';
import Router from 'koa-router';
import cors from 'koa2-cors';
import { sleep } from './utils/sleep.ts';

import text from './static/text.md?raw';

/* ② 允许所有来源跨域，也可以按需配置 */
const app = new Koa();
const router = new Router();
app.use(cors({ origin: '*' }));

app.use(router.routes());
app.use(router.allowedMethods());

router.post('/api', async (ctx) => {
    ctx.set({
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        Connection: 'keep-alive',
    });

    // 监听前端断开
    let closed = false;
    ctx.req.on('close', () => (closed = true));

    let temp = '';
    let count = 0;
    for (const line of text.split('\n')) {
        temp +=
            'data:' +
            JSON.stringify({
                data: { from: 'restful_answer', content: line },
            }) +
            '\n\n';
    }

    let startIndex = 0;
    let endIndex = 50;
    while (startIndex < temp.length) {
        if (closed) break;
        ctx.res.write(temp.slice(startIndex, endIndex));
        count++;
        startIndex = endIndex;
        endIndex += Math.ceil(Math.random() * 50);
        if (count % 20 === 0) {
            await sleep(1000);
        }
    }

    // 推送结束标记（前端根据 err_msg 停止循环）
    ctx.res.write(
        'data:' +
            JSON.stringify({ data: { from: 'err_msg', content: 'finish' } }) +
            '\n\n',
    );
    ctx.res.end();
});

app.listen(8080, () => {
    console.log('Server is running on port 8080.');
});
